package com.learning.servlet2x.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: RefererFilter
 * Description: 防盗链过滤器，需要使用到请求头 Referer
 * 简单实现只能 本站点访问
 * <p>
 * Date: 2014-12-9 21:16 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class RefererFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        // 必须的
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // 禁止缓存
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 链接来源地址，通过获取请求头 referer 得到
        String referer = request.getHeader("referer");
        System.out.println("获取的来源--->： " + referer);

        // 本站点访问，则有效
        if (referer == null || !referer.contains(request.getServerName())) {
            //如果 链接地址来自其他网站，则返回错误信息
            request.getRequestDispatcher("/error.gif").forward(request, response);
        } else {
            // 正常访问
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}
